<?php

$AppUI->savePlace();

$canEdit = !getDenyEdit( $m );
$canRead = !getDenyRead( $m );
if (!$canRead) {
	$AppUI->setMsg('Access denied', UI_MSG_ERROR);
	$AppUI->redirect();
}

$sql_table = 'contacts';

//Modify this mapping to match your LDAP->contact structure
//For instance, of you want the contact_phone2 field to be populated out of, say telephonenumber2 then you would just modify
//	'physicaldeliveryofficename' => 'contact_phone2',
// ro 
//	'telephonenumber2' => 'contact_phone2',

$sql_ldap_mapping = array(
	'givenname' => 'contact_first_name',
	'sn' => 'contact_last_name',
	'title' => 'contact_title',
	'companyname' => 'contact_company',
	'department' => 'contact_department',
	'employeeid' => 'contact_type',
	'mail' => 'contact_email',
	'telephonenumber' => 'contact_phone',
	'physicaldeliveryofficename' => 'contact_phone2',
	'postaladdress' => 'contact_address1',
	'l' => 'contact_city',
	'st' => 'contact_state',
	'postalcode' => 'contact_zip',
	'c' => 'contact_country'
);

$titleBlock = new CTitleBlock('Import Contacts from LDAP Directory');
$titleBlock->addButton('Main page', '?m=system');
$titleBlock->show();


if (isset( $_POST['server'] )) {
	$AppUI->setState( 'LDAPServer', $_POST['server'] );
}
$server = $AppUI->getState( 'LDAPServer', '' );

if (isset( $_POST['bind_name'] )) {
	$AppUI->setState( 'LDAPBindName', $_POST['bind_name'] );
}
$bind_name = $AppUI->getState( 'LDAPBindName', '' );

$bind_password = dPgetParam($_POST,'bind_password', '');

if (isset( $_POST['port'] )) {
	$AppUI->setState( 'LDAPPort', $_POST['port'] );
}
$port = $AppUI->getState( 'LDAPPort', '389' );

if (isset( $_POST['dn'] )) {
	$AppUI->setState( 'LDAPDN', $_POST['dn'] );
}
$dn = $AppUI->getState( 'LDAPDN', '' );

if (isset( $_POST['filter'] )) {
	$AppUI->setState( 'LDAPFilter', $_POST['filter'] );
}
$filter = $AppUI->getState( 'LDAPFilter',  '(objectclass=Person)');

$import = dPgetParam($_POST,'import');
$test = dPgetParam($_POST,'test');

$AppUI->setState('LDAPProto', dPgetParam($_POST, 'ldap_proto'));
$proto = $AppUI->getState('LDAPProto', '3');

?>
<form method="post">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
	<td class="tabon">LDAP Server information</td>
	<td width="100%">&nbsp;</td>
</tr>
</table>
<table border="0" cellpadding="7" cellspacing="0" width="100%" class="infopanel">
<tr>
	<td>
		<input type="submit" name="test" value="<?=$AppUI->_('Test Connection and Query')?>">
		<input type="submit" name="import" value="<?=$AppUI->_('Import Users')?>">
	</td>
</tr>
</table>
<table border="0" cellpadding="4" cellspacing="0" width="100%" class="subinfopanel">
	<tr>
		<td align="right"><?=$AppUI->_('Server')?>:</td>
		<td colspan="3" nowrap="nowrap">
			<table cellspacing="0" cellpadding="0" border="0">
			<tr>
				<td><input type="text" name="server" value="<?=$server?>" size="50"></td>
				<td style="padding-left: 8px;padding-right: 8px"><?=$AppUI->_('Port')?>:</td>
				<td><input type="text" name="port" value="<?=$port?>" size="4" maxlength="4"></td>
				<td style="padding-left: 8px;padding-right: 2px"><?=$AppUI->_('Protocol Version')?>:</td>
				<td><input type="radio" name="ldap_proto" value="2"<?=$proto == '2' ? ' checked="checked"' : ''?>></td>
				<td>2</td>
				<td><input type="radio" name="ldap_proto" value="3"<?=$proto == '3' ? ' checked="checked"' : ''?>></td>
				<td>3</td>
			</tr>
			</table>
		</td>
	</tr>
	<tr>
		<td align="right" nowrap="nowrap"><?=$AppUI->_('Bind Name')?>:</td>
		<td><input type="text" name="bind_name" value="<?=$bind_name?>" size="50"></td>
		<td align="right" nowrap="nowrap"><?=$AppUI->_('Password')?>:</td>
		<td width="100%"><input type="password" name="bind_password" value="<?=$bind_password?>" size="32"></td>
	</tr>
	<tr>
		<td align="right" nowrap="nowrap"><?=$AppUI->_('Base DN')?>:</td>
		<td colspan="3"><input type="text" name="dn" value="<?=$dn?>" size="105"></td>
	</tr>
	<tr>
		<td align="right" nowrap="nowrap"><?=$AppUI->_('Filter')?>:</td>
		<td colspan="3"><input type="text" name="filter" value="<?=$filter?>" size="105"></td>
	</tr>
</table>
<pre>
<?php
echo '<b>';
if(isset($test)){
	echo $test;
}
if(isset($import)){
	echo $import;
}
echo '</b><hr>';
if(isset($test) || isset($import)){

	$ds = @ldap_connect($server, $port);

	if (!$ds) {
		if (function_exists('ldap_error')) {
			print ldap_error($ds); 
		} else {
			print '<span style="color:red; font-weight:bold">ldap_connect failed.</span>';
		}
	} else {
		print 'ldap_connect succeeded<br/>';
	}

	ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, $proto);

	if(!@ldap_bind($ds,$bind_name,$bind_password)) {
		print '<span style="color:red;font-weight:bold">ldap_bind failed.</span>';
		if (function_exists('ldap_error')) {
			print ldap_error($ds).'<br/>';
		}
	} else {
		print 'ldap_bind successful.<br/>';
	}

	$return_types = array();
	foreach ($sql_ldap_mapping as $ldap => $sql) {
		$return_types[] = $ldap;
	}

	print 'basedn: '.$dn.'<br>';
	print 'expression: '.$filter.'<br>';

	$sr = @ldap_search($ds,$dn,$filter,$return_types);

	if($sr){
		print "Search completed Sucessfully.\n";
	} else {
		print "Search Error: [".ldap_errno($ds)."] ".ldap_error($ds)."\n";
	}


?>
</pre>
<?php
	//	print "Result Count:".(ldap_count_entries($ds,$sr))."\n";
	$info = ldap_get_entries($ds, $sr);
	if (!$info["count"]) {
		print "No users were found.\n";
	} else {
		print "Total Users Found:".$info["count"]."\n<hr>";
?>
<table border="0" cellpadding="3" cellspacing="0" width="100%" class="infopanel">
<?php
		if(isset($test)){
			foreach ($sql_ldap_mapping as $ldap => $sql) {
				print "<th>".$sql."</th>";
			}
		} else {
			$contacts = db_loadList( "SELECT contact_id, contact_first_name, contact_last_name FROM $sql_table" );
			foreach($contacts as $contact){
				$contact_list[$contact['contact_first_name']." ".$contact['contact_last_name']] = $contact['contact_id'];
			}
			unset($contacts);
		}

		for ($i = 0; $i<$info["count"]; $i++) {
			$pairs = array();
			print "<tr>\n";
			foreach ($sql_ldap_mapping as $ldap_name => $sql_name) {
				unset($val);
				if(isset($info[$i][$ldap_name][0])){
					$val = clean_value($info[$i][$ldap_name][0]);
				} 
				if(isset($val)){
					//if an email address is not specified in Domino you get a crazy value for this field that looks like FOO/BAR%NAME@domain.com  This'll filter those values out.
					if(isset($test) && $sql_name=="contact_email" && substr_count($val,"%")>0){
?>
						<td><span style="color:#880000;"><?=$AppUI->_('bad email address')?></span></td>
<?php
						continue;
					}
					$pairs[$sql_name] = $val;
					if(isset($test)){
?>
						<td><?=$val?></td>
<?php
					}
				} else {
?>
						<td>-</td>
<?php
				}
			}

			if(isset($import)){
				$pairs["contact_order_by"] = $pairs["contact_last_name"]." ".$pairs["contact_first_name"];
				//Check to see if this value already exists.
				if(isset($contact_list[$pairs["contact_first_name"]." ".$pairs["contact_last_name"]])){
					//if it does, remove the old one.
					$pairs["contact_id"] = $contact_list[$pairs["contact_first_name"]." ".$pairs["contact_last_name"]];
					db_updateArray( $sql_table, $pairs, "contact_id");
					echo "<td><span style=\"color:#880000;\">There is a duplicate record for ".$pairs["contact_first_name"]." ".$pairs["contact_last_name"].", the record has been updated.</span></td>\n";
				} else {
					echo "<td>Adding ".$pairs["contact_first_name"]." ".$pairs["contact_last_name"].".</td>\n";
					db_insertArray($sql_table,$pairs);
				}
			}
			print "</tr>\n";

	/*
			for ($ii=0; $ii<$info[$i]["count"]; $ii++){
				$data = $info[$i][$ii];
				for ($iii=0; $iii<$info[$i][$data]["count"]; $iii++) {
					echo $data.":&nbsp;&nbsp;".$info[$i][$data][$iii]."\n";
				}
			}
	 */
			echo "\n";
		}
	}
	echo "</table>";
	ldap_close($ds);
}

function clean_value($str){
	$bad_values = array("'");
	return str_replace($bad_values,"",$str);
}
?>
</table>
